package com.hengda.smart.speak.d.ac;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.hengda.smart.speak.d.App;
import com.hengda.smart.speak.d.R;
import com.hengda.smart.speak.d.base.BaseActivity;
import com.hengda.smart.speak.d.config.AppConfig;
import com.hengda.smart.speak.d.config.DbConfig;
import com.hengda.smart.speak.d.db.ResourceDb;
import com.hengda.smart.speak.d.fragment.AreaFragment;
import com.hengda.smart.speak.d.fragment.LocationFragment;
import com.hengda.smart.speak.d.fragment.MemberFragment;
import com.hengda.smart.speak.d.fragment.SettingFragment;
import com.hengda.smart.speak.d.service.MusicService;
import com.hengda.smart.speak.d.state.StateConstantAction;
import com.hengda.smart.speak.d.stc.StcLauncher;
import com.hengda.smart.speak.d.util.ParserUtil;
import com.hengda.smart.speak.d.util.SharePreferenceUtil;
import com.hengda.smart.speak.d.webservice.Webservice;

import org.kymjs.kjframe.utils.KJLoger;

import me.yokeyword.fragmentation.SupportActivity;
import me.yokeyword.fragmentation.SupportFragment;

public class MainActivity extends BaseActivity {
    private ImageView mIcoStateVolume;
    private TextView mTvStateVolume;
    private ImageView mIcoDeviceId;
    private TextView mTvStateGroupId;
    private TextView mTvStateBleNo;
    private ImageView mImgStateWifi;
    private ImageView mImgStatePower;
    private ImageView mImgStateChannel;
    private TextView mTvStateChannel;
    private FrameLayout mFlAll;
    private RadioGroup mRgAll;
    private RadioButton mRbArea;
    private RadioButton mRbLocation;
    private RadioButton mRbMember;
    private RadioButton mRbSetting;

    private SupportFragment[] mFragments = new SupportFragment[4];

    public static final int FIRST = 0;
    public static final int SECOND = 1;
    public static final int THIRD = 2;
    public static final int FOURTH = 3;

    int current_position = 0;
    int pre_position = 0;

    //==媒体音量
    private AudioManager audio;
    private int maxMediaVolume;
    private int currentMediaVolume;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
                WindowManager.LayoutParams. FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            mFragments[FIRST] = AreaFragment.newInstance();
            mFragments[SECOND] = LocationFragment.newInstance();
            mFragments[THIRD] = MemberFragment.newInstance();
            mFragments[FOURTH] = SettingFragment.newInstance();

            loadMultipleRootFragment(R.id.fl_all, FIRST,
                    mFragments[FIRST],
                    mFragments[SECOND],
                    mFragments[THIRD],
                    mFragments[FOURTH]);
        } else {
            // 这里库已经做了Fragment恢复,所有不需要额外的处理了, 不会出现重叠问题
            // 这里我们需要拿到mFragments的引用,也可以通过getSupportFragmentManager.getFragments()自行进行判断查找(效率更高些),用下面的方法查找更方便些
            mFragments[FIRST] = findFragment(AreaFragment.class);
            mFragments[SECOND] = findFragment(LocationFragment.class);
            mFragments[THIRD] = findFragment(MemberFragment.class);
            mFragments[FOURTH] = findFragment(SettingFragment.class);
        }
        initViews();
        initListener();
        initUtil();
        initMediaVolume();
        initService();
        initUi();
        initReceiver();
        initData();
    }

    //3工具类
    private StcLauncher lancherUtil;//STC下发工具
    private ParserUtil paserUtil;//解析工具
    private SharePreferenceUtil spUtil;	//当前配置文件信息
    private IntentFilter intentfilter;

    private void initUtil() {
        lancherUtil=new StcLauncher(App.getInstance(),this);
        spUtil=new SharePreferenceUtil(getApplicationContext(), AppConfig.SHARE_NAME);
        lancherUtil.openAudio();
        spUtil.setLocalAutoNo(0);
//		spUtil.setLoginState(false);
        paserUtil=ParserUtil.getInstance();
        //打开音频
//		openAudio();
    }




    private void initMediaVolume() {
        //音乐音量
        audio = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        maxMediaVolume = audio.getStreamMaxVolume( AudioManager.STREAM_MUSIC );
        currentMediaVolume = audio.getStreamVolume( AudioManager.STREAM_MUSIC );
        KJLoger.debug("MUSIC =max : " + maxMediaVolume + "current : " + currentMediaVolume);
        audio.setStreamVolume( AudioManager.STREAM_MUSIC , maxMediaVolume, AudioManager.FLAG_PLAY_SOUND );
        KJLoger.debug("MUSIC =max : " + maxMediaVolume + "current : " + currentMediaVolume);
    }

    private void initService() {
        //开启音频服务
        startService(new Intent(MainActivity.this,MusicService.class));

        if(spUtil.getSwitchLocation()){
//            startService(new Intent(this, Ble10GScanService.class));
        }
    }

    private void initListener() {
        mRgAll.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.rb_area:
                        showhide(0);
                        break;
                    case R.id.rb_location:
                        showhide(1);
                        break;
                    case R.id.rb_member:
                        showhide(2);
                        break;
                    case R.id.rb_setting:
                        showhide(3);
                        break;
                }
            }
        });
    }


    private void showhide(int position) {
        if (current_position != position) {
            pre_position = current_position;
            current_position = position;
            showHideFragment(mFragments[current_position], mFragments[pre_position]);
        }
    }


    private void initData() {
        ResourceDb.get_instance().OpenDB(DbConfig.DB_PATH);

    }

    private void initViews() {
        mIcoStateVolume = (ImageView) findViewById(R.id.ico_state_volume);
        mTvStateVolume = (TextView) findViewById(R.id.tv_state_volume);
        mIcoDeviceId = (ImageView) findViewById(R.id.ico_device_id);
        mTvStateGroupId = (TextView) findViewById(R.id.tv_state_group_id);
        mTvStateBleNo = (TextView) findViewById(R.id.tv_state_ble_no);
        mImgStateWifi = (ImageView) findViewById(R.id.img_state_wifi);
        mImgStatePower = (ImageView) findViewById(R.id.img_state_power);
        mImgStateChannel = (ImageView) findViewById(R.id.img_state_channel);
        mTvStateChannel = (TextView) findViewById(R.id.tv_state_channel);
        mFlAll = (FrameLayout) findViewById(R.id.fl_all);
        mRgAll = (RadioGroup) findViewById(R.id.rg_all);
        mRbArea = (RadioButton) findViewById(R.id.rb_area);
        mRbLocation = (RadioButton) findViewById(R.id.rb_location);
        mRbMember = (RadioButton) findViewById(R.id.rb_member);
        mRbSetting = (RadioButton) findViewById(R.id.rb_setting);
        mRbArea.setChecked(true);
    }

    private void initUi() {
        mTvStateVolume.setText(spUtil.getChannelVolume()+"");
        mTvStateChannel.setText(spUtil.getChannel0No()+"");
        mTvStateGroupId.setText(spUtil.getDeviceId()+"");
        if(isWifiConnected(getApplicationContext())){
            mImgStateWifi.setImageResource(R.mipmap.ico_wifi_on);
        }else{
            mImgStateWifi.setImageResource(R.mipmap.ico_wifi_off);
        }
    }

    private void initReceiver() {
        intentfilter=new IntentFilter();
        intentfilter.addAction(Webservice.Action.ACTION_LOGIN_SUCCESS);
        intentfilter.addAction(Intent.ACTION_BATTERY_CHANGED);
//        intentfilter.addAction(Ble10GScanService.ACTION_BLE_BEST);
        intentfilter.addAction(StateConstantAction.ACTION_CHANGE_VOLUME);
        intentfilter.addAction(StateConstantAction.ACTION_CHANGE_WIFIST);
        intentfilter.addAction(StateConstantAction.ACTION_CHANGE_GROUP_NO);
        intentfilter.addAction(StateConstantAction.ACTION_CHANGE_CHANNEL);
        intentfilter.addAction(StateConstantAction.ACTION_WIFI_CONN_OK);
        intentfilter.addAction(StateConstantAction.ACTION_WIFI_CONN_DIS);
        intentfilter.addAction(StateConstantAction.ACTION_CHANGE_CHANNEL);
        registerReceiver(receiver, intentfilter);
    }

    public static boolean isWifiConnected(Context context)
    {
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if(wifiNetworkInfo.isConnected())
        {
            return true ;
        }

        return false ;
    }


    /**
     *  主界面监听广播
     */
    private BroadcastReceiver receiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().contains(Intent.ACTION_BATTERY_CHANGED)) {
                int current = intent.getExtras().getInt("level");
                int total = intent.getExtras().getInt("scale");
                if (current >= 80) {
                    mImgStatePower.setImageResource(R.mipmap.ico_power_4);
                } else if (current >= 60 && current < 80) {
                    mImgStatePower.setImageResource(R.mipmap.ico_power_3);
                } else if (current >= 40 && current < 60) {
                    mImgStatePower.setImageResource(R.mipmap.ico_power_2);
                } else if (current >= 10 && current < 40) {
                    mImgStatePower.setImageResource(R.mipmap.ico_power_1);
                } else {
                    mImgStatePower.setImageResource(R.mipmap.ico_power_0);
                }
            }

            if(intent.getAction().equals(StateConstantAction.ACTION_CHANGE_GROUP_NO)){
                mTvStateGroupId.setText(spUtil.getDeviceId()+"");
            }

            if(intent.getAction().equals(StateConstantAction.ACTION_CHANGE_CHANNEL)){
                mTvStateChannel.setText(spUtil.getChannel0No()+"");
            }
            if(intent.getAction().equals(StateConstantAction.ACTION_CHANGE_VOLUME)){
                mTvStateVolume.setText(spUtil.getChannelVolume()+"");
            }

            if(intent.getAction().equals(StateConstantAction.ACTION_WIFI_CONN_DIS)){
                mImgStateWifi.setImageResource(R.mipmap.ico_wifi_off);
            }

            if(intent.getAction().equals(StateConstantAction.ACTION_WIFI_CONN_OK)){
                mImgStateWifi.setImageResource(R.mipmap.ico_wifi_on);
            }
//            if(intent.getAction().equals(Ble10GScanService.ACTION_BLE_BEST)){
////				bleNOTv.setText(intent.getStringExtra(Ble10GScanService.TAG_BLE_NO));
//            }
        }
    };



}
